<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button v-allow="'import-excel'" type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button v-allow="'export-excel'" type="danger" size="small" @click="exportExcel">excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table :data="list" :default-sort="{prop: 'timeOfEntry', order: 'descending'}" border>
          <el-table-column label="序号" width="50px" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="照骗">
            <template #default="{row}">
              <img v-imgerror="require('@/assets/common/img.jpeg')" :src="row.staffPhoto" alt="" style="width: 100px" @click="showCode(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{row}">
              {{ formaData(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <!-- <el-table-column label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push('/employees/detail/' + row.id)">查看</el-button>
              <el-button type="text" size="small" @click="hAssign(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="prev, pager, next"
            :current-page="page"
            :page-size="size"
            :total="total"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>

      <el-dialog
        v-if="showDialog"
        title="新增"
        :visible.sync="showDialog"
      >
        <empDialog
          @close="showDialog = false"
          @success="hSuccess"
        />
      </el-dialog>

      <!-- 二维码弹层 -->
      <el-dialog
        title="二维码"
        :visible.sync="showCodeDialog"
      >
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>

      <!-- 分配角色弹窗 -->
      <el-dialog
        title="角色分配"
        :visible.sync="assignRoleDialog"
      >
        <assignRole
          v-if="assignRoleDialog"
          :id="id"
          @success="assignRoleDialog = false"
        />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import assignRole from './assignRole.vue'
import QRCode from 'qrcode'
import empDialog from './empDialog.vue'
import { delEmployees, getEmployees } from '@/api/employees'
import employeesEnum from '@/constant/employees'
// console.log(employeesEnum.hireType)
const hireType = employeesEnum.hireType.reduce((prev, item) => {
  prev[item.id] = item.value
  return prev
}, {})
export default {
  components: {
    empDialog,
    assignRole
  },
  data() {
    return {
      list: [],
      page: 1,
      size: 10,
      total: 0,
      showDialog: false,
      showCodeDialog: false,
      assignRoleDialog: false,
      id: ''
    }
  },
  created() {
    this.loadEmployees()
  },
  methods: {
    hAssign(id) {
      this.assignRoleDialog = true
      this.id = id
    },
    showCode(url) {
      this.showCodeDialog = true
      this.$nextTick(() => {
        const canvas = this.$refs.myCanvas
        QRCode.toCanvas(canvas, url)
      })
    },
    exportExcel() {
      // 进行数据转换
      const { tHeader, data } = this.dataFormat(this.list)
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
      })
    },
    dataFormat(list) {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // header =  ['转正日期', '部门', '聘用形式', '编号', '手机号', '密码', '头像地址', '入职日期', '姓名', '工号']
      // 1. 获取表头
      const obj = list[0]
      const tHeader = Object.keys(obj).map(enKey => {
        return mapInfo[enKey]
      })
      // console.log(tHeader)

      const data = list.map(item => {
        return Object.values(item)
      })
      // console.log(data)
      return { tHeader, data }
    },
    hDel(id) {
      this.$confirm('确定删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await delEmployees(id)
        // console.log(res)
        if (res.code !== 10000) return this.$message.warning(res.message)
        this.$message.success(res.message)
        if (this.list.length === 1) {
          this.page--
          if (this.page <= 0) {
            this.page = 1
          }
        }
        this.loadEmployees()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    hSuccess() {
      this.total++
      const maxPage = Math.ceil(this.total / this.size)
      this.page = maxPage
      this.loadEmployees()
      this.showDialog = false
    },
    formaData(id) {
      return hireType[id]
    },
    handleCurrentChange(val) {
      // console.log(val)
      this.page = val
      this.loadEmployees()
    },
    async loadEmployees() {
      try {
        const res = await getEmployees({ page: this.page, size: this.size })
        // console.log(res)
        if (res.code !== 10000) return this.$message.warning(res.message)
        this.$message.success(res.message)
        this.list = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>
